import { Component, OnInit } from '@angular/core';
import {InventoryService} from "../inventory.service";
import {ConfirmationService} from "primeng/primeng";
import {StorageService} from "../../services/storage.service";
import {ActivatedRoute, Router} from "@angular/router";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-equipment-storage',
  templateUrl: './equipment-storage.component.html',
  styleUrls: ['./equipment-storage.component.scss']
})
export class EquipmentStorageComponent implements OnInit {
  showAddStorage: boolean = false;       //新增录入
  showWarehouseManager: boolean = false;  //选择仓库管理员弹框
  showLocation: boolean = false;  //选择仓库管理员弹框
  cols;
  coles;
  submitData;
  currentMaterial;
  dataSource = [];
  totalRecords;
  borrowData = [];
  inspections = [];
  state;
  selectInsepections = [];
  viewState; //保存入库总览页面操作按钮
  chooseCids;
  title = '入库申请';
  sid;
  treeState;
  editDataSource=[];
  personalData=[];
  editInspections;
  inventoryForm :  FormGroup;
  fb: FormBuilder = new FormBuilder();

  constructor( private inventoryService: InventoryService,
               private confirmationService: ConfirmationService,
               private storageService:StorageService,
               private router:Router,
               private route:ActivatedRoute,
               private eventBusService:EventBusService
               ) {}

  ngOnInit() {
    this.inventoryForm = this.fb.group({
      'sid': [''],
      'keeper_pid': [''],
      'inspectiondepartment': ['', Validators.required],
      'keeper':[''],
      'remarks':[''],
      'approve_remarks':[''],
    })
    this.submitData = {
      "sid": "",
      "location": "",
      "location_id": "",
      "keeper": "",
      "keeper_pid": "",
      "remarks":"",
      "inventories": []
    }
    this.viewState = 'apply'; // 入库申请状态

    this.cols = [
      {field: 'pn', header: '编号'},
      {field: 'name', header: '名称'},
      {field: 'catagory', header: '分类'},
      {field: 'brand', header: '品牌'},
      {field: 'model', header: '型号'},
      {field: 'specification', header: '规格'},
      {field: 'quantity', header: '数量'},
      {field: 'supplier', header: '供应商'},
    ];
    this.coles = [
      {field: 'pn', header: '编号'},
      {field: 'name', header: '名称'},
      {field: 'catagory', header: '分类'},
      {field: 'brand', header: '品牌'},
      {field: 'model', header: '型号'},
      {field: 'specification', header: '规格'},
      {field: 'quantity', header: '数量'},
      {field: 'supplier', header: '供应商'},
      {field: 'location', header: '库存位置'},
    ];
    this.route.queryParams.subscribe(params=>{
      this.viewState = 'apply';
      if(params['sid'] && params['title']&&params['state']){
        this.title = params['title'];
        this.sid = params['sid'];
        this.viewState = params['state'];
        this.inventoryService.queryStorage(this.sid).subscribe(data=>{
          this.borrowData = data;
          console.log(this.borrowData);
          this.editDataSource = this.borrowData['inventories']?this.borrowData['inventories']:[];
          if(!this.editDataSource){
            this.editDataSource = [];
            this.editInspections =[];
            this.totalRecords = 0;
          }
          this.editInspections = this.editDataSource.slice(0,10);
          this.totalRecords = this.editDataSource.length;
        })
      }
    });
    this.querylogin();
  }

  updategoBack() {
    let sid =  this.borrowData['sid'];
    this.borrowData['status'] = "";
    this.eventBusService.flow.next(this.borrowData['status']);
    this.router.navigate(['../overview'],{queryParams:{sid:sid,state:'viewDetail',title:'入库总览'},relativeTo:this.route})
  }
  goBack() {
    let sid =  this.borrowData['sid'];
    this.borrowData['status'] = "";
    this.eventBusService.flow.next(this.borrowData['status']);
    this.router.navigate(['../overview'],{queryParams:{sid:sid,state:'viewDetail',title:'入库总览'},relativeTo:this.route})
  }
  //查询登录人
  querylogin(){
    this.inventoryService.queryPersonal().subscribe(data=>{
      this.personalData = data;
      console.log(this.personalData)
    });
  }
  showAddStorageMask(state){
    this.state = 'add';
    this.showAddStorage = true;
  }
  closeAddStorageMask(bool){
    this.showAddStorage = bool;
  }
  showLoactionMask(){
    this.treeState = 'add';
    this.showLocation = true;
  }
  updateOption(currentMaterial,state,index){
    this.state = state;
    this.currentMaterial = currentMaterial;
    console.log(this.currentMaterial)
    this.storageService.setCurrentStorage('storageindex',index);
    this.showAddStorage = true;
  }

  // 提交
  addStorageSubmint(submitData,dataSource){
    let inventories = [];
    for(let i = 0;i<dataSource.length;i++){
      let temp = dataSource[i];
      let obj = {};
      obj['pn'] = temp['pn'];
      obj['unit_cost'] = temp['unit_cost'];
      obj['quantity'] = temp['quantity']+"";
      obj['time_purchase'] = temp['time_purchase'];
      inventories.push(obj);
    }
    submitData.inventories = inventories;
    this.inventoryService.addStorage(submitData).subscribe(() =>{
      this.router.navigate(['../overview'],{queryParams:{title:'入库总览'},relativeTo:this.route})

    },(err:Error)=>{
       let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  addStorage(storage){
    this.dataSource.push(storage);
    this.inspections = this.dataSource.slice(0,10);
    this.totalRecords = this.dataSource.length;
    this.editDataSource.push(storage);
    this.editInspections = this.editDataSource.slice(0,10);
    this.totalRecords = this.editDataSource.length;
    this.showAddStorage = false;
  }
  updateStorage(storage){
    let index = this.storageService.getCurrentStorage('storageindex');
    if(this.viewState ==='update'){
      // this.editDataSource.push(storage);
      this.editDataSource[index] = storage;
      this.editInspections = this.editDataSource.slice(0,10);
      this.showAddStorage = false;
    }
    this.dataSource[index] = storage;
    this.inspections = this.dataSource.slice(0,10);
    this.showAddStorage = false;
  }

  loadCarsLazy(event) {
    //in a real application, make a remote request to load data using state metadata from event
    //event.first = First row offset
    //event.rows = Number of rows per page
    //event.sortField = Field name to sort with
    //event.sortOrder = Sort order as number, 1 for asc and -1 for dec
    //filters: FilterMetadata object having field as key and filter value, filter matchMode as value

    //imitate db connection over a network
    setTimeout(() => {
      if(this.dataSource) {
        this.inspections = this.dataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  editloadCarsLazy(event) {
    //in a real application, make a remote request to load data using state metadata from event
    //event.first = First row offset
    //event.rows = Number of rows per page
    //event.sortField = Field name to sort with
    //event.sortOrder = Sort order as number, 1 for asc and -1 for dec
    //filters: FilterMetadata object having field as key and filter value, filter matchMode as value

    //imitate db connection over a network
    setTimeout(() => {
      if(this.editDataSource) {
        this.editInspections = this.editDataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  //保存
  addDeviceSave(data){
    let inventories = [];
    for(let i = 0;i<this.dataSource.length;i++){
      let temp = this.dataSource[i];
      let obj = {};
      obj['pn'] = temp['pn'];
      obj['unit_cost'] = temp['unit_cost'];
      obj['quantity'] = temp['quantity']+"";
      obj['time_purchase'] = temp['time_purchase'];
      inventories.push(obj);
    }
    data.inventories = inventories;
    this.inventoryService.queryStorageSave(data).subscribe(data=>{
      this.router.navigate(['../overview'],{queryParams:{title:'入库总览'},relativeTo:this.route})

    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  deleteStorage(){
      for(let i = 0;i<this.selectInsepections.length;i++){
        for(let j = 0;j<this.dataSource.length;j++){
          if(this.selectInsepections[i]['sid']===this.dataSource[j]['sid']){
            this.dataSource.splice(j,1);
            this.inspections = this.dataSource.slice(0,10);
            this.selectInsepections = [];
          }
        }
      }

  }

  updateDeleteStorage(){
      let editDataSource =this.editDataSource.slice();
      for(let i = 0;i<this.selectInsepections.length;i++){
        for(let j = 0;j<editDataSource.length;j++){
          if(this.selectInsepections[i]['pn']===editDataSource[j]['pn']){
            this.editDataSource.splice(j,1);
            this.editInspections = this.editDataSource.slice(0,10);
            break;
          }
        }
      }
      this.selectInsepections = [];

  }
  nodeTree(node){
    this.submitData.location = node['label'];
    this.submitData.location_id = node['did'];
    this.borrowData['location'] = node['label'];
    this.borrowData['location_id'] = node['did'];
    this.showLocation =false;
  }
  //  仓库管理员
  showWarehouseManagerMask(){
    this.showWarehouseManager = !this.showWarehouseManager;
  }
  closeWarehouseManagerMask(bool){
    this.showWarehouseManager = bool;
  }
  closeLocationMask(bool){
    this.showLocation = bool;
  }
  //修改保存方法
  updateDeviceSave(submitData,dataSource){
    let inventories = [];
    for(let i = 0;i<dataSource.length;i++){
      let temp = dataSource[i];
      let obj = {};
      obj['sid'] = temp['sid'];
      obj['location'] = temp['location'];
      obj['location_id'] = temp['location_id'];
      obj['keeper'] = temp['keeper'];
      obj['keeprer_pid'] = temp['keeprer_pid'];
      obj['unit_cost'] = temp['unit_cost'];
      obj['quantity'] = temp['quantity']+"";
      obj['pn'] = temp['pn'];
      obj['name'] = temp['name'];
      obj['catagory'] = temp['catagory'];
      obj['supplier'] = temp['supplier'];
      obj['brand'] = temp['brand'];
      obj['model'] = temp['model'];
      obj['time_purchase'] = temp['time_purchase'];
      obj['specification'] = temp['specification'];
      inventories.push(obj);
    }
    submitData.inventories = inventories;
    this.inventoryService.updateStorage(submitData).subscribe(data=>{
      this.router.navigate(['../overview'],{queryParams:{title:'入库总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  formSave(){
    if(this.viewState === 'apply'){
      this.addDeviceSave(this.submitData);
    }else if(this.viewState === 'update'){
        this.updateDeviceSave(this.borrowData,this.editDataSource);
      // this.addDeviceSave(this.storageData)

    }

  }
  formSubmit(){
    if(this.viewState === 'apply'){
      this.addStorageSubmint(this.submitData,this.dataSource);
    }else if(this.viewState === 'update'){
      this.addStorageSubmint(this.borrowData,this.editDataSource);
    }

  }

  clearTreeDialog () {
    this.submitData.location = '';
    this.submitData.location_id = '';
    this.borrowData['location'] = ''
    this.borrowData['location_id'] = ''
  }
}
